import { IBaseContentPage } from '@lib/IBaseIssuePage';
import { SSLib } from '@lib/SSLib';
import * as $ from 'jquery';
import './issuesPage.less';

export class MergeRequestsPage implements IBaseContentPage {
    constructor() {
        ;
    }

    public IsMatch(url: string) {
        return /merge_requests\/\d/.test(url);
    }

    public Execute() {
        init();
    }
}

function init() {
    let $btnTemp = $('<button type="button" class="btn btn-sm btn-primary">Slayer Merge</button>');
    let $btnMergeRequest = $('.accept-merge-request');
    $btnMergeRequest.closest('.btn-group').hide().after($btnTemp);

    $btnTemp[0].addEventListener('click', e => {
        // /root/gitlabtest/tree/2-first-02-33
        let sourceBranchHref = $('.js-source-branch a').attr('href');

        let sourceBranch = sourceBranchHref.substr(sourceBranchHref.lastIndexOf('/') + 1);

        // // 如果议题名称是数字开头，需要填写estimate和spent
        // if (!isNaN(sourceBranch[0] as any)) {
        //     if ($('.time-tracking-comparison-pane').length <= 0) {
        //         alert("estimate和spent不能为空");
        //         return false;
        //     }
        // }

        let targetBranch = $('.js-target-branch').text().trim();
        
        if (targetBranch === "master") {
            let content: string = ($('.qa-description')[0] || $('.js-task-list-container')[0]).textContent;

            if (content.indexOf('<!-- UPDATE_LOG_START -->') <= 0 || content.indexOf('<!-- UPDATE_LOG_END -->') <= 0) {
                alert("合并到master的merge request，需要包含特定注释");
                return false;
            }
        }

        merge();

        function merge() {
            $btnMergeRequest.closest('.btn-group').show();
            $btnTemp.hide();

            $btnMergeRequest[0].dispatchEvent(new CustomEvent('click'));
        }
    }, true);
}
